#include "AT24Cxx.h"

int AT24Cxx::check()
{
    i2c->loadSlave(decive_addr);
    return i2c->check();
}

size_t AT24Cxx::write(uint8_t data)
{
    if (write_addr > 255)
    {
        return AT24Cxx_WRITE_ADDRESS_OUT;
    }
    i2c->loadSlave(decive_addr);
    return i2c->write(write_addr++, data);
}

size_t AT24Cxx::write(const uint8_t *buffer, size_t size)
{
    if (write_addr > 255)
    {
        return AT24Cxx_WRITE_ADDRESS_OUT;
    }
    i2c->loadSlave(decive_addr);
    size = size < (256 - write_addr) ? size : (256 - write_addr);
    uint16_t end_addr = write_addr + size;
    while (1)
    {
        uint16_t write_end_addr = write_addr + 8;
        write_end_addr /= 8;
        write_end_addr *= 8;
        write_end_addr = write_end_addr > end_addr ? end_addr : write_end_addr;
        uint16_t write_size = write_end_addr - write_addr;
        i2c->write(write_addr, buffer, write_size);
        write_addr = write_end_addr;
        buffer += write_size;
        if (write_end_addr == end_addr)
            break;
    }
    return size;
}

int16_t AT24Cxx::read()
{
    if (read_addr > 255)
    {
        return AT24Cxx_READ_ERROR;
    }
    i2c->loadSlave(decive_addr);
    return i2c->read(read_addr++);
}

int16_t AT24Cxx::read(uint8_t *buf, size_t size)
{
    if (read_addr > 255)
    {
        return AT24Cxx_READ_ERROR;
    }
    i2c->loadSlave(decive_addr);
    size = size < (256 - read_addr) ? size : (256 - read_addr);

    size_t res = i2c->read(read_addr, buf, size);
    if (res == 0xfffe)
    {
        return 0;
    }
    read_addr += size;
    return size;
}
